import { Button, Form, Input, Popconfirm, Table, DatePicker, Select, InputNumber } from 'antd';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { openNotification_util, checkdatavalid_util, fetchsync_util, useCallbackState ,addkey_for_mxdata} from '../util/util.js'
import Upload_hooks from './upload_hooks'
import Popup_table_hooks_datas from './popup_table_hooks_datas'
import { v4 as uuidv4 } from 'uuid';

import moment from 'moment'
import locale from 'antd/lib/date-picker/locale/zh_CN'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')

const { Option } = Select;





const Edit_table_hook = (props) => {
  const [dataSource, setDataSource] = useState([]);
  const [count, setCount] = useState(props.datasource.length + 2);
  const [selectedRows, setselectedRows] = useState([])
  const [selectedRowKeys, setselectedRowKeys] = useState([])
  const [columns, setcolumns] = useState([])
  const [wlmcdatasource, setwlmcdatasource] = useState([]);
  const [popupdatas,setpopupdatas]=useState({})


  const handleDelete = (record) => {
    const newData = dataSource.filter((item) => item.key !== record.key);
    setDataSource(newData);
    props.handgetmxdata(newData)
    props.handledelid(record.id)
  };

    //加载popup数据源
    const loadpopupdata = async () => {
      //console.log("***************加载了popup数据源!!!!!!!!!!!!!!!!!!**************")
      var newv_wlmcdatasource = []
      let vmxrtdata = await fetchsync_util("/admin/qbmes_new/getpopupview", 'POST', { viewname: "v_qb_fqbq_all" }, "json")
      setwlmcdatasource(vmxrtdata.resultdata)
    }

    useEffect(() => {
      loadpopupdata();
    }, [])


  useEffect(() => {
    setDataSource(props.datasource)
  }, [props.datasource])



  useEffect(() => {
    //重新渲染table
    renrendercolumns()
  }, [dataSource,wlmcdatasource])


  const rowSelection = {
    selectedRowKeys: props.selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      props.handleselectson(selectedRows, selectedRowKeys)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE]
  };



  //自定义渲染
  const renrendercolumns = () => {

    var newcolumns = props.colmuns.map((col) => {

      if (col.inputType == "input_item") {
        col.render = (text, record, index) => {
          return  <Input  defaultValue={text} style={col.style?col.style:{}}
          onBlur={e => { handleChangeinput(e, col.dataIndex, text, record, index) }} />
        }
      }
      else if (col.inputType == "popup_item_datas") {
        col.render = (text, record, index) => {
          return <Popup_table_hooks_datas viewname={col.popup_viewname} selecttype="radio"
          tablecolnum={col.popup_column}  datas={wlmcdatasource}
          ifshow="none" popup_maintitle={col.popup_maintitle} 
          handlechange={e => { handleChangepopup(e, col.popup_tansferarr,col.dataIndex, text, record, index) }}
          inputvalue={text} />
        }
      }
      else if (col.inputType == "select_item") {
        col.render = (text, record, index) => {
          var optionitem = col.selectdata.map(obj => <Option value={obj.value}>{obj.label}</Option>)
          return <Select placeholder="" value={text} style={col.style?col.style:{}}
            onSelect={e => { handleSelect(e, col.dataIndex, text, record, index) }}>
            {optionitem}
          </Select>
        }
      }
      else if (col.inputType == "date_item") {
        col.render = (text, record, index) => {
          return <DatePicker locale={locale} value={text==""?"":moment(text)} style={col.style?col.style:{}}
            onChange={(e, datestring) => { handleChangedate(e, datestring, col.dataIndex, text, record, index) }} />
        }
      }
      else if (col.inputType == "normal_item") {
        col.render = (text, record, index) => text
      }
      else if (col.inputType == "upload_item") {
        col.render = (text, record, index) => {
          return <Upload_hooks handleback={tpurl => getchildvalue_upload(tpurl, col.dataIndex, text, record, index)}
            title="" initpxtpurl={text} />
        }
      }

      
      else if (col.inputType == "deletetool_item") {
        col.render = (text, record, index) => {
          return <Popconfirm title="确定要删除么?" onConfirm={() => handleDelete(record)}>
            <Button><a style={{ fontWeight: "600", color: "#C54444" }}>删 除</a></Button>
          </Popconfirm>
        }
      }
      else if (col.inputType == "readonly") {
        col.render = (text, record, index) => {
          return <Input value={text} disabled
          />
        }
      }

      return {
        ...col
      };
    });


    setcolumns(newcolumns)
  }



  //从upload取值
  const getchildvalue_upload = (tpurl, dataIndex, text, record, index) => {

    var newdatasource = [...dataSource];
    const realindex = newdatasource.findIndex((item) => record.key === item.key);
    newdatasource[realindex][dataIndex] = tpurl;
    setDataSource(newdatasource)
    props.handgetmxdata(newdatasource)
  }

  //监听日期
  const handleChangedate = (e, datestr, dataIndex, text, record, index) => {
    var newdatasource = [...dataSource];
    const realindex = newdatasource.findIndex((item) => record.key === item.key);
    newdatasource[realindex][dataIndex] = datestr;
    setDataSource(newdatasource)
    props.handgetmxdata(newdatasource)
  }

  //监听输入及联动
  const handleChangeinput = (e, dataIndex, text, record, index) => {
    var newdatasource = [...dataSource];
    const realindex = newdatasource.findIndex((item) => record.key === item.key);
    newdatasource[realindex][dataIndex] = e.target.value;
    setDataSource(newdatasource)
    props.handgetmxdata(newdatasource)
  }


    //监听输入及联动
    const handleChangepopup = (e, transferarr,dataIndex, text, record, index) => {

      var tansferarr = transferarr;
      var selectrow = e;
var newformdata = {}
tansferarr.forEach(item => {
  record[item.target]= selectrow[item.origin]
})

      var newdatasource = [...dataSource];
      const realindex = newdatasource.findIndex((item) => record.key === item.key);
      newdatasource[realindex] = record;
      //console.log("newdatasource",newdatasource)
      setDataSource(newdatasource)
      props.handgetmxdata(newdatasource)
      
      
    }
  
  


  //监听选择
  const handleSelect = (e, dataIndex, text, record, index) => {
    var newdatasource = [...dataSource];
    const realindex = newdatasource.findIndex((item) => record.key === item.key);
    newdatasource[realindex][dataIndex] = e;
    setDataSource(newdatasource)
    props.handgetmxdata(newdatasource)

  }


  const handleAdd = () => {
    const uniqueId = uuidv4();
 var newData={key:uniqueId}
props.colmuns.forEach(item=>{
 
  if(item.inputType!=="date_item"){
    newData[item.dataIndex]=""}
    else{
      newData[item.dataIndex]=""}

})
    setDataSource([...dataSource, newData]);
    props.handgetmxdata([...dataSource, newData])

    setCount(count + 1);
  };

  const handleSave = () => {
    // const newData = [...dataSource];
    // const index = newData.findIndex((item) => row.key === item.key);
    // const item = newData[index];
    // newData.splice(index, 1, {
    //   ...item,
    //   ...row,
    // });
    // setDataSource(newData);
   //console.log(dataSource)

  };



  return (
    <div style={props.styleobj?props.styleobj:{}}>
      <Button onClick={handleAdd} style={{
        backgroundColor: "white",
         marginLeft: "0.5rem", color: "#a91f24", fontWeight: "800"
      }} >新增</Button>
      <Button onClick={handleSave} style={{
        backgroundColor: "white",
        marginLeft:  "0.5rem", color: "#a91f24", fontWeight: "800"
      }} >查看明细表数据</Button>

      <Table  style={{width:"100%"}}
        rowSelection={rowSelection}
        bordered
        dataSource={dataSource}
        columns={columns}
      />
    </div>
  );
};
export default Edit_table_hook;


